package com.example.wishstar.repository;

import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.example.wishstar.api.Api;
import com.example.wishstar.db.UserDao;
import com.example.wishstar.model.User;
import com.example.wishstar.utils.ApiResponse;
import com.example.wishstar.view.activity.LoginActivity;
import com.google.gson.JsonObject;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UserRepository
{
    private String TAG = this.getClass().getName();
    private UserDao userDao;
    private Api api;

    public UserRepository(UserDao userDao, Api api)
    {
        this.api = api;
        this.userDao = userDao;
    }

    public interface LoginCallBack {
        void callback(Response<ApiResponse<Integer>> response);
        void throwablecallback(Throwable t);
    }

    public void login(String user_mail, String password, LoginCallBack loginCallBack)
    {
        JsonObject fieldMap = new JsonObject();
        fieldMap.addProperty("password", password);
        fieldMap.addProperty("userMail", user_mail);
        api.login(RequestBody.create(MediaType.parse("application/json"), fieldMap.toString())).enqueue(new Callback<ApiResponse<Integer>>()
        {
            @Override
            public void onResponse(Call<ApiResponse<Integer>> call, Response<ApiResponse<Integer>> response) {
                Log.e(TAG, "1");
                if(response.body() != null) {
                    loginCallBack.callback(response);
                    if(response.body().code == 200) {
                        insertUser(response.body(), user_mail, password, 1);
                    }
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<Integer>> call, Throwable t) {
                Log.e(TAG, "2");
                loginCallBack.throwablecallback(t);
            }
        });
    }

    private void insertUser(ApiResponse<Integer> response, String user_mail, String password, int state)
    {
        AsyncTask.execute(new Runnable()
        {
            @Override
            public void run()
            {
                User user = new User(response.getData(), user_mail, password, state);
                userDao.insertUser(user);
                Log.e(TAG, "insertUser()->" + user);
            }
        });
    }

}
